package cn.bjxy.shishaolong.system.user.service;

import cn.bjxy.shishaolong.common.StatusCode;
import cn.bjxy.shishaolong.common.SysConst;
import cn.bjxy.shishaolong.system.exception.OperatorFailureException;
import cn.bjxy.shishaolong.system.user.entity.SysAdmin;
import cn.bjxy.shishaolong.system.user.entity.SysUserInfo;
import cn.bjxy.shishaolong.system.user.mapper.SysAdminMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Formatter;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 时少龙
 * @since 2019-03-09
 */
@Service
public class SysAdminServiceImpl extends ServiceImpl<SysAdminMapper, SysAdmin> implements ISysAdminService {

    @Autowired
    private SysAdminMapper sysAdminMapper;

    @Autowired
    private ISysUserInfoService userInfoService;

    @Override
    public IPage<SysAdmin> queryByCondition(IPage<SysAdmin> page, SysAdmin sysAdmin) {
        List<SysAdmin> adminList = sysAdminMapper.queryByCondition(page, sysAdmin);
        return page.setRecords(adminList);
    }

    @Override
    public List<SysAdmin> queryByCondition(SysAdmin sysAdmin) {
        return sysAdminMapper.queryByCondition(sysAdmin);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean remove(String ids) {
        Boolean flag = true;
        for (String id: ids.split(",")) {
            // 对管理员表逻辑删除
            flag = this.update(new UpdateWrapper<SysAdmin>()
                    .set("deleted_at", LocalDateTime.now()).eq("tid", id));

            // 对用户基本信息表进行逻辑删除
            SysAdmin sysAdmin = sysAdminMapper.selectById(id);
            flag = userInfoService.update(new UpdateWrapper<SysUserInfo>()
                    .set("deleted_at", LocalDateTime.now()).eq("tid", sysAdmin.getUserId()));
        }
        return flag;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePassword(SysAdmin sysAdmin) {
        if(!this.checkOldPassword(sysAdmin)){
            throw new OperatorFailureException(StatusCode.OLD_PASSWORD_ERROR,StatusCode.OLD_PASSWORD_ERROR_MSG);
        }

        //再进行更新操作
        int password = sysAdminMapper.update(sysAdmin, new UpdateWrapper<SysAdmin>().lambda()
                .set(SysAdmin::getPassword, sysAdmin.getNewPassword())
                .eq(SysAdmin::getTid, sysAdmin.getTid()));

        if(password < 1){
            throw new OperatorFailureException(StatusCode.UPDATE_FAILURE,StatusCode.UPDATE_FAILURE_MSG);
        }
    }

    @Override
    public Boolean checkOldPassword(SysAdmin sysAdmin) {
        //先验证旧密码
        SysAdmin sysAdminTemp = sysAdminMapper.selectOne(new QueryWrapper<SysAdmin>().lambda()
                .eq(SysAdmin::getTid, sysAdmin.getTid())
                .eq(SysAdmin::getPassword, sysAdmin.getOldPassword()));
        return sysAdminTemp == null ? false : true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean save(SysAdmin sysAdmin) {

        sysAdmin.setUpdateAt(LocalDateTime.now());
        SysUserInfo sysUserInfo = new SysUserInfo();
        SysAdmin adminCopy = new SysAdmin();

        if (sysAdmin.getTid() == null) {  // 新建

            // 1.拷贝用户信息
            this.copyProperty(sysAdmin,sysUserInfo,adminCopy);

            // 2.保存用户基本信息。并关联到管理员
            userInfoService.save(sysUserInfo);
            adminCopy.setUserId(sysUserInfo.getTid());

            // 3.设置管理员工号
            adminCopy.setWorkNo(getAdminWorkNo());

            // 4.新增
            sysAdminMapper.insert(adminCopy);

        } else {  // 修改
            // 1.拷贝用户信息 包含基本信息id，管理员id，管理员工号
            this.copyProperty(sysAdmin,sysUserInfo,adminCopy);
            sysUserInfo.setTid(sysAdmin.getUserId());
            adminCopy.setTid(sysAdmin.getTid()).setWorkNo(sysAdmin.getWorkNo());

            // 2.保存修改
            userInfoService.updateById(sysUserInfo);
            sysAdminMapper.updateById(adminCopy);
        }
        return true;
    }

    /**
     * 生成管理员工号
     * @return
     */
    private String getAdminWorkNo() {
        Integer count = sysAdminMapper.selectCount(null);
        Formatter formatter = new Formatter();
        return formatter.format(SysConst.ADMIN_WORK_NO_PREFIX + "%04d", count).toString();
    }

    /**
     * 将用户的所有信息分别复制到 管理员实体和用户基本信息实体中。
     * @param allUserInfo 存着用户所有信息的实体
     * @param userInfo 用户基本信息实体
     * @param copyAdmin 管理员信息实体
     */
    private void copyProperty(SysAdmin allUserInfo, SysUserInfo userInfo,SysAdmin copyAdmin){
        // 1.复制用户基本信息
        userInfo.setName(allUserInfo.getName()).setPhone(allUserInfo.getPhone()).setEmail(allUserInfo.getEmail())
                .setSex(allUserInfo.getSex()).setBirthday(allUserInfo.getBirthday()).setUpdateAt(allUserInfo.getUpdateAt());
        // 2.复制管理员信息
        copyAdmin.setUpdateAt(allUserInfo.getUpdateAt());
    }
}
